<?php
/**
 *+------------------
 * Ingenious
 *+------------------
 * Copyright (c) https://gitee.com/ingenstream/ingenious  All rights reserved.
 *+------------------
 * Author: Mr. April (405784684@qq.com)
 *+------------------
 * Software Registration Number: 2024SR0694589
 * Official Website: http://www.ingenstream.cn
 */

namespace madong\laravel\wf\model;

use madong\laravel\wf\basic\BaseModel;
use madong\ingenious\interface\model\IProcessTaskActor;

class ProcessTaskActorHistory extends BaseModel implements IProcessTaskActor
{

    /**
     * 数据表主键
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 表名
     *
     * @var string
     */
    protected $table = 'wf_process_task_actor_history';

    /**
     * 是否自增id
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * 是否指定时间戳
     *
     * @var bool
     */
    public $timestamps = true;

    // 自定义时间戳字段
    const CREATED_AT = 'create_time'; // 自定义创建时间字段
    const UPDATED_AT = 'update_time'; // 自定义更新时间字段

    protected $appends = ['instance_state', 'create_date', 'update_date'];

    protected $fillable = [
        'id',
        'process_task_id',
        'actor_id',
        'create_time',
        'create_by',
        'update_time',
        'update_by',
    ];

    /**
     * 定义访问器
     *
     * @return null
     */
    public function getInstanceStateAttribute(): mixed
    {
        return $this->instance->state ?? null;
    }

    /**
     * ID-搜索器
     *
     * @param $query
     * @param $value
     */
    public function scopeId($query, $value)
    {
        if (!empty($value)) {
            $query->where('id', $value);
        }
    }

    /**
     * 流程任务ID-搜索器
     *
     * @param $query
     * @param $value
     */
    public function scopeProcessTaskId($query, $value)
    {
        if (!empty($value)) {
            $query->where('process_task_id', $value);
        }
    }

    /**
     * 参与者ID-搜索器
     *
     * @param $query
     * @param $value
     */
    public function scopeActorId($query, $value)
    {
        if (!empty($value)) {
            $query->where('actor_id', $value);
        }
    }

    /**
     * 流程任务用户-关联任务task
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function task(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(ProcessTaskHistory::class, 'process_task_id');
    }

    public function instance(): \Illuminate\Database\Eloquent\Relations\HasOneThrough
    {
        return $this->hasOneThrough(
            ProcessInstanceHistory::class,
            ProcessTaskHistory::class,
            'id', // ProcessTaskHistory 的外键
            'id', // ProcessInstanceHistory 的外键
            'process_task_id', // 当前模型的本地键
            'process_instance_id' // 目标模型的本地键
        );
    }

}
